<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/"
      v-if="isApiUrlConfigured" />
    <div class="q-pb-md text-h5">设置</div>
    <q-banner class="text-white bg-info q-mb-sm" dense inline-actions v-if="!isApiUrlConfigured">
      在使用前必须先设置好API服务地址，如有疑问，请与软件供应商联系
    </q-banner>
    <div class="row q-pt-sm q-col-gutter-sm">
      <div class="row col-12">
        <div class="col-12">
          <q-icon color="red" name="fas fa-asterisk" size="10px" />
          <span>API服务地址</span>
          <q-input :error="v$.apiUrl.$error" :error-message="e$(v$.apiUrl.$errors)" :hide-bottom-space="true" dense
            ref="apiUrl" autofocus outlined square stack-label v-model="$d.apiUrl" clearable no-error-icon :maxlength="300"
            @keyup.enter="focusHelper.onEntered(1)"/>
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <span>NLP地址</span>
          <easy-input v-model="$d.nlpUrl" :error="v$.nlpUrl.$error" :error-message="e$(v$.nlpUrl.$errors)" :maxlength="300"
            :ref="el=>focusHelper.regRef(el, 2)" @keyup.enter="focusHelper.onEntered(2)"/>
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <span>电子秤地址</span>
          <easy-input v-model="$d.electronicScaleUrl" :error="v$.electronicScaleUrl.$error"
            :error-message="e$(v$.electronicScaleUrl.$errors)" :maxlength="300"
            :ref="el=>focusHelper.regRef(el, 3)" @keyup.enter="focusHelper.onEntered(3)"/>
        </div>
      </div>
      <div class="row col-12">
        <div class="col-12">
          <q-btn class="full-width" color="primary" label="确定" @click="onOk" :loading="loadingState" />
        </div>
      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'PdaConfigStd'
}
</script>

<script lang="ts" setup>

import {computed, reactive, ref, nextTick} from 'vue'
import useVuelidate from '@vuelidate/core'
import {playErrorSound} from '@njt/wms/helper/audio'
import { useFocusNextHelper } from '@njt/foundation/hooks/focusHelper'

let loadingState = ref(false)

const $d = reactive({
  apiUrl: '',
  nlpUrl: '',
  electronicScaleUrl: '',
  urlRegex: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/
})

const valResult = reactive({
  apiUrl: '',
})
const validators = $f.validators
const rules = {
  apiUrl: {
    required: validators.required,
    regex: validators.regex($d.urlRegex)
  },
  nlpUrl: {
    regex: validators.regex($d.urlRegex)
  },
  electronicScaleUrl: {
    regex: validators.regex($d.urlRegex)
  }
}

const v$ = useVuelidate(rules, computed(() => $d), {$autoDirty: true, $externalResults: valResult, $scope: false})

const onOk = function () {
  void v$.value.$validate()
    .then((valRes) => {
      if (valRes) {
        loadingState.value = true
        $f.feAxios
          .get<string>($d.apiUrl + '/comm/about/get-about-info')
          .then((result) => {
            const reg = /^[\w\u4E00-\u9FA5]+\s\([\w\.\-_]+\)\s[\d\.]+\s\([\d\.]+\)$/
            if (reg.test(result.data)) {
              localStorage.setItem('apiUrl', $d.apiUrl)
              $f.axios.defaults.baseURL = $d.apiUrl
              localStorage.setItem('nlpUrl', $d.nlpUrl)
              localStorage.setItem('electronicScaleUrl', $d.electronicScaleUrl)
              void $f.router.push({name: 'index'})
            } else {
              playErrorSound()
              valResult.apiUrl = 'API地址格式未通过验证'
              void nextTick(() => {
                apiUrl.value?.focus()
              })
            }
          })
          .catch((err) => {
            console.log(err)
            playErrorSound()
            valResult.apiUrl = 'API地址请求失败'
            void nextTick(() => {
              apiUrl.value?.focus()
            })
          })
          .finally(() => {
            loadingState.value = false
          })
      }
    })
}

const isApiUrlConfigured = computed(() => {
  return !!localStorage.getItem('apiUrl')
})

$d.apiUrl = localStorage.getItem('apiUrl') || ''
$d.nlpUrl = localStorage.getItem('nlpUrl') || ''
$d.electronicScaleUrl = localStorage.getItem('electronicScaleUrl') || ''

const apiUrl = ref<HTMLElement>()
const e$ = $f.getFieldErrStr
const focusHelper = useFocusNextHelper()
focusHelper.regRef(apiUrl, 1)
</script>

<style scoped>

</style>
